layui.config({
    base: "static/layui/module/",
}).extend({
    excel: 'excel/excel'
}).use(['form','layer','jquery','table','upload','excel','laytpl','element'],function() {
    var layer = layui.layer,
        $ = layui.jquery,
        upload = layui.upload,
        element = layui.element,
        excel = layui.excel,
        laytpl = layui.laytpl,
        table = layui.table;

    table.on('toolbar(table)', function(obj){
        tableToolbarEnvent(obj);
        switch(obj.event){
            case 'import':
                layer.confirm('确认导入？', {
                        btn: ['覆盖导入','取消'] //按钮
                    }
                    ,function () {
                        $("#uploadExcel")[0].click();
                    })
                break;
        };
    });

    upload.render({
        elem: '#uploadExcel'
        ,accept: 'file' //普通文件
        ,exts: 'xlsx|xls'
        ,auto: false
        ,choose: function(obj){
            var files = obj.pushFile()
            var fileArr = Object.values(files)// 注意这里的数据需要是数组，所以需要转换一下
            var fields = {
                'material' : 'B',
                'materialSum' : 'C',
            }
            // 用完就清理掉，避免多次选中相同文件时出现问题
            for (var index in files) {
                if (files.hasOwnProperty(index)) {
                    delete files[index]
                }
            }
            $('#uploadExcel').next().val('');
            uploadExcel('/stock-now/upload/',fields,fileArr,excel,layer,laytpl,element)
        }
    });

    function uploadExcel(url,fields,files,excel,layer,laytpl,element) {
        try {
            excel.importExcel(files, {
                // 读取数据的同时梳理数据
                fields : fields
            }, function(data) {
                // 如果不需要展示直接上传，可以再次 $.ajax() 将JSON数据通过 JSON.stringify() 处理后传递到后端即可
                var sheetTab = undefined;

                layer.open({
                    title : '文件转换结果',
                    type: 1,
                    btn: ["确定","取消"],
                    area: [ '80%', '60%' ],
                    tipsMore : true,
                    content : laytpl($('#LAY-excel-export-ans').html()).render({
                        data : data,
                        files : files
                    }),
                    success : function(layero, index) {
                        element.on('tab(sheet)', function(data){
                            sheetTab = this.getAttribute('lay-id');
                        });
                    }
                    ,yes: function(index, layero){
                        let itm = layer.load(0, { shade: 0.3 });
                        if(sheetTab == undefined){
                            layer.msg("请先选择要导入的sheet页！",{icon:2});
                            return;
                        }
                        var result = data[0][sheetTab];
                        if(result.length < 3){
                            layer.msg("导入的sheet页没有数据！",{icon:2});
                            return;
                        }
                        var pushData = [];
                        $.each(result,function(index,e){
                            if(index > 1){
                                pushData.push(e);
                            }
                        });
                        var count = 0;
                        for(var i in pushData[0]) {
                            if(pushData[0].hasOwnProperty(i)) {
                                count++;
                            }
                        }
                        var dateField = [];
                        for(var i in fields) {
                            if(fields.hasOwnProperty(i)) {
                                count--;
                            }
                            if(fields[i].indexOf('time') || fields[i].indexOf('Time') || fields[i].indexOf('date') || fields[i].indexOf('Date')){
                                dateField.push(fields[i]);
                            }
                        }
                        if(count != 0){
                            alert('导入模板错误,导出的excel即为导入的模板！');
                            return;
                        }
                        try {
                            $.post(url, {data: JSON.stringify(pushData)}, function (d) {
                                if (d.code == '200') { //上传成功
                                    if (d.data) {
                                        layer.alert("导入成功,存在共用物料,请联系管理员核对！");
                                    } else {
                                        layer.alert("导入成功！");
                                    }
                                    table.reload('table');
                                } else {
                                    layer.alert("导入失败," + d.msg);
                                }
                            });
                        } catch (e) {
                            layer.alert("系统异常！");
                        } finally {
                            layer.close(itm)
                        }
                        layer.close(index); //如果设定了yes回调，需进行手工关闭
                    }
                })
            })
        } catch (e) {
            layer.alert(e.message)
        }
    }
})